---
title: "在Shell中执行SQL脚本（并传递密码）"
date: 2019-7-10
categories:
- mysql
tags:
---

<div id="content">
<blockquote>
<p>
<a href="https://stackoverflow.com/questions/8055694/how-to-execute-a-mysql-command-from-a-shell-script">https://stackoverflow.com/questions/8055694/how-to-execute-a-mysql-command-from-a-shell-script</a>
</p>
</blockquote>
<p>
mysql命令的-p选项用于指定密码，用在shell脚本中，-p和密码之间不能有空格。
</p>
<p>
You need to use the -p flag to send a password. And it's tricky because you must have no space between -p and the password.
</p>
<div class="org-src-container">
<pre class="src src-shell">$ mysql -h <span style="font-style: italic;">"server-name"</span> -u <span style="font-style: italic;">"root"</span> <span style="font-style: italic;">"-pXXXXXXXX"</span> <span style="font-style: italic;">"database-name"</span> &lt; <span style="font-style: italic;">"filename.sql"</span>
</pre>
</div>
<p>
If you use a space after -p it makes the mysql client prompt you interactively for the password, and then it interprets the next command argument as a database-name:
</p>
<div class="org-src-container">
<pre class="src src-shell">$ mysql -h <span style="font-style: italic;">"server-name"</span> -u <span style="font-style: italic;">"root"</span> -p <span style="font-style: italic;">"XXXXXXXX"</span> <span style="font-style: italic;">"database-name"</span> &lt; <span style="font-style: italic;">"filename.sql"</span>
</pre>
</div>
<p>
Enter password: &lt;you type it in here&gt;
ERROR 1049 (42000): Unknown database 'XXXXXXXX'
</p>
<p>
Actually, I prefer to store the user and password in ~/.my.cnf so I don't have to put it on the command-line at all:
</p>
<div class="org-src-container">
<pre class="src src-conf">[<span style="font-weight: bold; text-decoration: underline;">client</span>]
<span style="font-weight: bold; font-style: italic;">user</span> = root
<span style="font-weight: bold; font-style: italic;">password</span> = XXXXXXXX
</pre>
</div>
<p>
Then:
</p>
<div class="org-src-container">
<pre class="src src-sh">$ mysql -h <span style="font-style: italic;">"server-name"</span> <span style="font-style: italic;">"database-name"</span> &lt; <span style="font-style: italic;">"filename.sql"</span>
</pre>
</div>
</div>
<div class="status" id="postamble">
<p class="date">Date: 2019-7-10</p>
<p class="author">Author: amo</p>
<p class="validation"><a href="http://validator.w3.org/check?uri=referer">Validate</a></p>
</div>
